# 配置Windows防火墙规则
# 需要管理员权限运行
# 使用方法: 以管理员身份运行PowerShell，然后执行 .\scripts\setup-firewall.ps1

# 检查管理员权限
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "❌ 此脚本需要管理员权限运行" -ForegroundColor Red
    Write-Host "请以管理员身份运行PowerShell" -ForegroundColor Yellow
    exit 1
}

Write-Host "🔥 配置Windows防火墙规则..." -ForegroundColor Cyan

# 删除旧规则（如果存在）
$rules = @(
    "Video Conference Web",
    "Video Conference API",
    "Video Conference RTC UDP",
    "Video Conference RTC TCP"
)

foreach ($ruleName in $rules) {
    try {
        Remove-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue
    } catch {
        # 规则不存在，忽略错误
    }
}

# 添加新规则
Write-Host "`n📝 添加防火墙规则..." -ForegroundColor Yellow

# Web前端端口
try {
    New-NetFirewallRule -DisplayName "Video Conference Web" `
        -Direction Inbound `
        -Action Allow `
        -Protocol TCP `
        -LocalPort 3100 `
        -Profile Any `
        -Enabled True | Out-Null
    Write-Host "✅ 已允许端口 3100 (Web前端)" -ForegroundColor Green
} catch {
    Write-Host "❌ 添加规则失败: $_" -ForegroundColor Red
}

# API服务端口
try {
    New-NetFirewallRule -DisplayName "Video Conference API" `
        -Direction Inbound `
        -Action Allow `
        -Protocol TCP `
        -LocalPort 3101 `
        -Profile Any `
        -Enabled True | Out-Null
    Write-Host "✅ 已允许端口 3101 (API服务)" -ForegroundColor Green
} catch {
    Write-Host "❌ 添加规则失败: $_" -ForegroundColor Red
}

# RTC端口 UDP
try {
    New-NetFirewallRule -DisplayName "Video Conference RTC UDP" `
        -Direction Inbound `
        -Action Allow `
        -Protocol UDP `
        -LocalPort 3102-3110 `
        -Profile Any `
        -Enabled True | Out-Null
    Write-Host "✅ 已允许端口 3102-3110 UDP (RTC媒体传输)" -ForegroundColor Green
} catch {
    Write-Host "❌ 添加规则失败: $_" -ForegroundColor Red
}

# RTC端口 TCP
try {
    New-NetFirewallRule -DisplayName "Video Conference RTC TCP" `
        -Direction Inbound `
        -Action Allow `
        -Protocol TCP `
        -LocalPort 3102-3110 `
        -Profile Any `
        -Enabled True | Out-Null
    Write-Host "✅ 已允许端口 3102-3110 TCP (RTC媒体传输)" -ForegroundColor Green
} catch {
    Write-Host "❌ 添加规则失败: $_" -ForegroundColor Red
}

Write-Host "`n✅ 防火墙配置完成！" -ForegroundColor Green
Write-Host "`n已开放的端口:" -ForegroundColor Cyan
Write-Host "  3100     - Web前端" -ForegroundColor White
Write-Host "  3101     - API服务" -ForegroundColor White
Write-Host "  3102-3110 - RTC媒体传输 (UDP/TCP)" -ForegroundColor White

Write-Host "`n💡 提示:" -ForegroundColor Yellow
Write-Host "  - 如果使用云服务器，还需要在云平台控制台配置安全组规则" -ForegroundColor White
Write-Host "  - 如果使用路由器，需要配置端口转发" -ForegroundColor White

